<?php

namespace common\components\easy_wechat;

/**
 * 公众号发送模板消息
 * https://easywechat.com/5.x/official-account/template_message.html#%E5%8F%91%E9%80%81%E6%A8%A1%E6%9D%BF%E6%B6%88%E6%81%AF
 */
abstract class WxgzhTMessage implements WxgzhTMessageApi
{
    protected $gzhComponentId;

    protected $templateId;

    public $toUserOpenid;

    protected $url;

    protected $miniprogramAppid;

    protected $miniprogramPagepath;

    protected $_conf;

    public function send()
    {
        if (!$this->toUserOpenid || !$this->templateId) {
            throw new \Exception("必须配置toUserOpenid和templateId");
        }
        $conf = [
            'touser' => $this->toUserOpenid,
            'template_id' => $this->templateId,
        ];
        if ($this->url) {
            $conf['url'] = $this->url;
        }
        if ($this->miniprogramAppid) {
            if (!$this->miniprogramPagepath) {
                throw new \Exception("必须配置miniprogramPagepath");
            }
            unset($conf['url']);
            $conf['miniprogram'] = [
                'appid' => $this->miniprogramAppid,
                'pagepath' => $this->miniprogramPagepath,
            ];
        }
        $this->_conf = $conf;
        $this->setDataConf();
        /** @var EasyWechat $gzhComponent */
        $gzhComponent = \Yii::$app->get($this->gzhComponentId);
        $gzhApp = $gzhComponent->gzhApp;
        $gzhApp->template_message->send($this->_conf);
    }
}